<?php
/**
 * Popup to add a new contact
 * 
 */

use Hive\Mission\Partner;
use Fox\Popup;
use Fox\Dao\SqlFragment;
use Fox\Html\DropList;
use Hive\Mission;
use Fox\Html\Input;
use Fox\Html\Block;
use Fox\Html\Screen;
use Fox\Generator;

$xview = Xview::instance();
$id = $xview->val('missionid');
$screen = new Screen('sAddContact','add',null,true,Generator::ajaxReload('MC_gContacts',
			Generator::url('missions','contacts','list',array('missionid' => $id))));
			
$block = new Block('bAddContact');
$block->add(new Input('name',true))
		->autocomplete(Generator::url('contacts','autocomplete'),null,'partnerid')
		->add(new Input('partnerid'))->hidden();
// Role 
$finder = new Mission\Partner\Role();
$block->add(new DropList(array('mission_role','role'),true,false,true))
		->options($finder->find(new SqlFragment('language = ?',
				array($xview->language()))),
		'role','label')
		->unsetOption(array(Partner::ROLE_CANDIDATE,
								Partner::ROLE_RESPONSIBLE,
								Partner::ROLE_ACCOUNT));
				
$block->noLegend();
$screen->add($block);

if($screen->submitted()) {

	$fields = $screen->get();
	// Check if the contact already exist ?
	if(!empty($fields['partnerid']))
	{
		
	} else {
		// Contact Does not Exist 
		$url = Generator::url('ressource','add',null,array('name1' => $fields['name']));
		Fox\Message::Error(Msg(Hive::BUNDLE,
							Hive::CONTACT_DOES_NOT_EXIST_YET,
							$fields['name'],
							$url));
	}
			
	if(!$screen->errors()) {
		try {
			/* @var $mission Hive\Mission */
			$mission = Xview::instance()->component('missions', 'object');
			$partner = new Partner();
			$partner->setFields(array('partnerid' => $fields['partnerid'],
										'role' => $fields['role']));
			$mission->addToPartners($partner);
			$mission->prepareUpdate(Mission::CHANGE_ADD_PARTNER);
			$mission->update();
			Fox\Message::Success(Msg(Hive::BUNDLE,
									Hive::MISSION_MSG_ADD_PARTNER,
									$fields['name'],
									$mission->label()
					));
			echo $xview->messages();
			exit;
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Errors::pushMessage($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Errors::pushMessage($e);
		}
	}
}			
// Popup
$popup = new Popup('add',Msg(Hive::BUNDLE,Hive::MISSION_ADD_PARTNER),$screen,500);
echo $popup->display();
